1a2ddcc96e5b9c32c227ae69120fad1c60daac05
4 * Created on Sep 7, 2006
6 * API for MediaWiki 1.8+
8 * Copyright © 2006 Yuri Astrakhan <Firstname><Lastname>@gmail.com
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
23 * http://www.gnu.org/copyleft/gpl.html
26 if ( !defined( 'MEDIAWIKI' ) ) {
27 // Eclipse helper - will be ignored in production
28 require_once( 'ApiBase.php' );
32 * This is a base class for all Query modules.
33 * It provides some common functionality such as constructing various SQL
38 abstract class ApiQueryBase
extends ApiBase
{
40 private $mQueryModule, $mDb, $tables, $where, $fields, $options, $join_conds;
42 public function __construct( $query, $moduleName, $paramPrefix = '' ) {
43 parent
::__construct( $query->getMain(), $moduleName, $paramPrefix );
44 $this->mQueryModule
= $query;
46 $this->resetQueryParams();
50 * Get the cache mode for the data generated by this module. Override this
51 * in the module subclass.
53 * Public caching will only be allowed if *all* the modules that supply
54 * data for a given request return a cache mode of public.
56 public function getCacheMode( $params ) {
61 * Blank the internal arrays with query parameters
63 protected function resetQueryParams() {
64 $this->tables
= array();
65 $this->where
= array();
66 $this->fields
= array();
67 $this->options
= array();
68 $this->join_conds
= array();
72 * Add a set of tables to the internal array
73 * @param $tables mixed Table name or array of table names
74 * @param $alias mixed Table alias, or null for no alias. Cannot be
75 * used with multiple tables
77 protected function addTables( $tables, $alias = null ) {
78 if ( is_array( $tables ) ) {
79 if ( !is_null( $alias ) ) {
80 ApiBase
::dieDebug( __METHOD__
, 'Multiple table aliases not supported' );
82 $this->tables
= array_merge( $this->tables
, $tables );
84 if ( !is_null( $alias ) ) {
85 $tables = $this->getAliasedName( $tables, $alias );
87 $this->tables
[] = $tables;
92 * Get the SQL for a table name with alias
93 * @param $table string Table name
94 * @param $alias string Alias
97 protected function getAliasedName( $table, $alias ) {
98 return $this->getDB()->tableName( $table ) . ' ' . $alias;
102 * Add a set of JOIN conditions to the internal array
104 * JOIN conditions are formatted as array( tablename => array(jointype,
105 * conditions) e.g. array('page' => array('LEFT JOIN',
106 * 'page_id=rev_page')) . conditions may be a string or an
107 * addWhere()-style array
108 * @param $join_conds array JOIN conditions
110 protected function addJoinConds( $join_conds ) {
111 if ( !is_array( $join_conds ) ) {
112 ApiBase
::dieDebug( __METHOD__
, 'Join conditions have to be arrays' );
114 $this->join_conds
= array_merge( $this->join_conds
, $join_conds );
118 * Add a set of fields to select to the internal array
119 * @param $value mixed Field name or array of field names
121 protected function addFields( $value ) {
122 if ( is_array( $value ) ) {
123 $this->fields
= array_merge( $this->fields
, $value );
125 $this->fields
[] = $value;
130 * Same as addFields(), but add the fields only if a condition is met
131 * @param $value mixed See addFields()
132 * @param $condition bool If false, do nothing
133 * @return bool $condition
135 protected function addFieldsIf( $value, $condition ) {
137 $this->addFields( $value );
144 * Add a set of WHERE clauses to the internal array.
145 * Clauses can be formatted as 'foo=bar' or array('foo' => 'bar'),
146 * the latter only works if the value is a constant (i.e. not another field)
148 * If $value is an empty array, this function does nothing.
150 * For example, array('foo=bar', 'baz' => 3, 'bla' => 'foo') translates
151 * to "foo=bar AND baz='3' AND bla='foo'"
152 * @param $value mixed String or array
154 protected function addWhere( $value ) {
155 if ( is_array( $value ) ) {
156 // Sanity check: don't insert empty arrays,
157 // Database::makeList() chokes on them
158 if ( count( $value ) ) {
159 $this->where
= array_merge( $this->where
, $value );
162 $this->where
[] = $value;
167 * Same as addWhere(), but add the WHERE clauses only if a condition is met
168 * @param $value mixed See addWhere()
169 * @param $condition boolIf false, do nothing
170 * @return bool $condition
172 protected function addWhereIf( $value, $condition ) {
174 $this->addWhere( $value );
181 * Equivalent to addWhere(array($field => $value))
182 * @param $field string Field name
183 * @param $value string Value; ignored if null or empty array;
185 protected function addWhereFld( $field, $value ) {
186 // Use count() to its full documented capabilities to simultaneously
187 // test for null, empty array or empty countable object
188 if ( count( $value ) ) {
189 $this->where
[$field] = $value;
194 * Add a WHERE clause corresponding to a range, and an ORDER BY
195 * clause to sort in the right direction
196 * @param $field string Field name
197 * @param $dir string If 'newer', sort in ascending order, otherwise
198 * sort in descending order
199 * @param $start string Value to start the list at. If $dir == 'newer'
200 * this is the lower boundary, otherwise it's the upper boundary
201 * @param $end string Value to end the list at. If $dir == 'newer' this
202 * is the upper boundary, otherwise it's the lower boundary
203 * @param $sort bool If false, don't add an ORDER BY clause
205 protected function addWhereRange( $field, $dir, $start, $end, $sort = true ) {
206 $isDirNewer = ( $dir === 'newer' );
207 $after = ( $isDirNewer ?
'>=' : '<=' );
208 $before = ( $isDirNewer ?
'<=' : '>=' );
209 $db = $this->getDB();
211 if ( !is_null( $start ) ) {
212 $this->addWhere( $field . $after . $db->addQuotes( $start ) );
215 if ( !is_null( $end ) ) {
216 $this->addWhere( $field . $before . $db->addQuotes( $end ) );
220 $order = $field . ( $isDirNewer ?
'' : ' DESC' );
221 if ( !isset( $this->options
['ORDER BY'] ) ) {
222 $this->addOption( 'ORDER BY', $order );
224 $this->addOption( 'ORDER BY', $this->options
['ORDER BY'] . ', ' . $order );
230 * Add an option such as LIMIT or USE INDEX. If an option was set
231 * before, the old value will be overwritten
232 * @param $name string Option name
233 * @param $value string Option value
235 protected function addOption( $name, $value = null ) {
236 if ( is_null( $value ) ) {
237 $this->options
[] = $name;
239 $this->options
[$name] = $value;
244 * Execute a SELECT query based on the values in the internal arrays
245 * @param $method string Function the query should be attributed to.
246 * You should usually use __METHOD__ here
247 * @return ResultWrapper
249 protected function select( $method ) {
250 // getDB has its own profileDBIn/Out calls
251 $db = $this->getDB();
253 $this->profileDBIn();
254 $res = $db->select( $this->tables
, $this->fields
, $this->where
, $method, $this->options
, $this->join_conds
);
255 $this->profileDBOut();
261 * Estimate the row count for the SELECT query that would be run if we
262 * called select() right now, and check if it's acceptable.
263 * @return bool true if acceptable, false otherwise
265 protected function checkRowCount() {
266 $db = $this->getDB();
267 $this->profileDBIn();
268 $rowcount = $db->estimateRowCount( $this->tables
, $this->fields
, $this->where
, __METHOD__
, $this->options
);
269 $this->profileDBOut();
271 global $wgAPIMaxDBRows;
272 if ( $rowcount > $wgAPIMaxDBRows ) {
279 * Add information (title and namespace) about a Title object to a
281 * @param $arr array Result array à la ApiResult
282 * @param $title Title
283 * @param $prefix string Module prefix
285 public static function addTitleInfo( &$arr, $title, $prefix = '' ) {
286 $arr[$prefix . 'ns'] = intval( $title->getNamespace() );
287 $arr[$prefix . 'title'] = $title->getPrefixedText();
291 * Override this method to request extra fields from the pageSet
292 * using $pageSet->requestField('fieldName')
293 * @param $pageSet ApiPageSet
295 public function requestExtraData( $pageSet ) {
299 * Get the main Query module
302 public function getQuery() {
303 return $this->mQueryModule
;
307 * Add a sub-element under the page element with the given page ID
308 * @param $pageId int Page ID
309 * @param $data array Data array à la ApiResult
310 * @return bool Whether the element fit in the result
312 protected function addPageSubItems( $pageId, $data ) {
313 $result = $this->getResult();
314 $result->setIndexedTagName( $data, $this->getModulePrefix() );
315 return $result->addValue( array( 'query', 'pages', intval( $pageId ) ),
316 $this->getModuleName(),
321 * Same as addPageSubItems(), but one element of $data at a time
322 * @param $pageId int Page ID
323 * @param $item array Data array à la ApiResult
324 * @param $elemname string XML element name. If null, getModuleName()
326 * @return bool Whether the element fit in the result
328 protected function addPageSubItem( $pageId, $item, $elemname = null ) {
329 if ( is_null( $elemname ) ) {
330 $elemname = $this->getModulePrefix();
332 $result = $this->getResult();
333 $fit = $result->addValue( array( 'query', 'pages', $pageId,
334 $this->getModuleName() ), null, $item );
338 $result->setIndexedTagName_internal( array( 'query', 'pages', $pageId,
339 $this->getModuleName() ), $elemname );
344 * Set a query-continue value
345 * @param $paramName string Parameter name
346 * @param $paramValue string Parameter value
348 protected function setContinueEnumParameter( $paramName, $paramValue ) {
349 $paramName = $this->encodeParamName( $paramName );
350 $msg = array( $paramName => $paramValue );
351 $this->getResult()->disableSizeCheck();
352 $this->getResult()->addValue( 'query-continue', $this->getModuleName(), $msg );
353 $this->getResult()->enableSizeCheck();
357 * Get the Query database connection (read-only)
360 protected function getDB() {
361 if ( is_null( $this->mDb
) ) {
362 $this->mDb
= $this->getQuery()->getDB();
368 * Selects the query database connection with the given name.
369 * See ApiQuery::getNamedDB() for more information
370 * @param $name string Name to assign to the database connection
371 * @param $db int One of the DB_* constants
372 * @param $groups array Query groups
375 public function selectNamedDB( $name, $db, $groups ) {
376 $this->mDb
= $this->getQuery()->getNamedDB( $name, $db, $groups );
380 * Get the PageSet object to work on
383 protected function getPageSet() {
384 return $this->getQuery()->getPageSet();
388 * Convert a title to a DB key
389 * @param $title string Page title with spaces
390 * @return string Page title with underscores
392 public function titleToKey( $title ) {
393 // Don't throw an error if we got an empty string
394 if ( trim( $title ) == '' ) {
397 $t = Title
::newFromText( $title );
399 $this->dieUsageMsg( array( 'invalidtitle', $title ) );
401 return $t->getPrefixedDbKey();
405 * The inverse of titleToKey()
406 * @param $key string Page title with underscores
407 * @return string Page title with spaces
409 public function keyToTitle( $key ) {
410 // Don't throw an error if we got an empty string
411 if ( trim( $key ) == '' ) {
414 $t = Title
::newFromDbKey( $key );
415 // This really shouldn't happen but we gotta check anyway
417 $this->dieUsageMsg( array( 'invalidtitle', $key ) );
419 return $t->getPrefixedText();
423 * An alternative to titleToKey() that doesn't trim trailing spaces
424 * @param $titlePart string Title part with spaces
425 * @return string Title part with underscores
427 public function titlePartToKey( $titlePart ) {
428 return substr( $this->titleToKey( $titlePart . 'x' ), 0, - 1 );
432 * An alternative to keyToTitle() that doesn't trim trailing spaces
433 * @param $keyPart string Key part with spaces
434 * @return string Key part with underscores
436 public function keyPartToTitle( $keyPart ) {
437 return substr( $this->keyToTitle( $keyPart . 'x' ), 0, - 1 );
440 public function getPossibleErrors() {
441 return array_merge( parent
::getPossibleErrors(), array(
442 array( 'invalidtitle', 'title' ),
443 array( 'invalidtitle', 'key' ),
448 * Get version string for use in the API help output
451 public static function getBaseVersion() {
452 return __CLASS__
. ': $Id$';
459 abstract class ApiQueryGeneratorBase
extends ApiQueryBase
{
461 private $mIsGenerator;
463 public function __construct( $query, $moduleName, $paramPrefix = '' ) {
464 parent
::__construct( $query, $moduleName, $paramPrefix );
465 $this->mIsGenerator
= false;
469 * Switch this module to generator mode. By default, generator mode is
470 * switched off and the module acts like a normal query module.
472 public function setGeneratorMode() {
473 $this->mIsGenerator
= true;
477 * Overrides base class to prepend 'g' to every generator parameter
478 * @param $paramName string Parameter name
479 * @return string Prefixed parameter name
481 public function encodeParamName( $paramName ) {
482 if ( $this->mIsGenerator
) {
483 return 'g' . parent
::encodeParamName( $paramName );
485 return parent
::encodeParamName( $paramName );
490 * Execute this module as a generator
491 * @param $resultPageSet ApiPageSet: All output should be appended to
494 public abstract function executeGenerator( $resultPageSet );